package com.sskj.level.ui.activity;


import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.TradeInfoBean;
import com.sskj.level.bean.TradeListBean;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.TradeActivityPresenter;
import com.sskj.level.util.CoinUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.TipUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.LEVEL_TRADE)//交易单界面
public class TradeActivity extends BaseActivity<TradeActivityPresenter> {
    @Inject
    UserViewModel userViewModel;
    @BindView(R2.id.slidingTabLayout)
    CommonTabLayout slidingTabLayout;
    ArrayList<Fragment> mFragments;
    private Disposable subscribe;

    @Autowired
    public String code;
    private MaterialDialog allTip;
    private int curPos = 0;
    private UserData userData;
    private BigDecimal winLossMoney;

    private List<TradeListBean> list;
    private TradeInfoBean bean;
    private Disposable changePriceDispo;

    @Override
    protected int getLayoutId() {
        return R.layout.level_activity_trade;
    }

    @Override
    public TradeActivityPresenter getPresenter() {
        return new TradeActivityPresenter();
    }

    @Override
    protected void initView() {
        DaggerUserDataComponent.create().inject(this);
        ARouter.getInstance().inject(this);
        code = null;
        setTitle(App.INSTANCE.getString(R.string.leveltradeActivity1));
        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.leveltradeActivity2), 0, 0));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.leveltradeActivity3), 0, 0));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.leveltradeActivity4), 0, 0));
        mFragments = new ArrayList<>();
        mFragments.add((Fragment) ARouter.getInstance().build(RConfig.LEVEL_FRAGMENT_HOLDER)
                .withString(Constans.STOCK_CODE, code)
                .navigation());
        mFragments.add((Fragment) ARouter.getInstance().build(RConfig.LEVEL_FRAGMENT_ENTRUST)
                .withString(Constans.STOCK_CODE, code)
                .navigation());
        mFragments.add((Fragment) ARouter.getInstance().build(RConfig.LEVEL_FRAGMENT_DEAL)
                .withString(Constans.STOCK_CODE, code)
                .navigation());
        slidingTabLayout.setTabData(tabItems, this, R.id.tradeFrameLayout, mFragments);
        slidingTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                mPresenter.getRisk();
                mPresenter.getAllList();


            } else {
                userData = null;
            }
        });


        startTimer();
    }

    @Override
    protected void initData() {
        super.initData();

        LiveDataBus.get().with(RxBusCode.PUSH_COIN_BEAN_BIBI, CoinBean.class)
                .observe(this, this::refreshCoin);
    }




    private void startTimer() {
        DisposUtil.close(subscribe);
        subscribe = Flowable.interval(0, 5, TimeUnit.SECONDS)
                .onBackpressureDrop()
                .subscribe(i -> {
                    mPresenter.getRisk();
                    mPresenter.getAllList();
                });
    }

    private void setItem(int itemId, String title, String content) {
        ((TextView) findViewById(itemId).findViewById(R.id.tv_title)).setText(title);
        ((TextView) findViewById(itemId).findViewById(R.id.tv_content)).setText(content);
    }

    private void setItem(int itemId, String title, String content, String a) {
        ((TextView) findViewById(itemId).findViewById(R.id.tv_title)).setText(title);
        ((TextView) findViewById(itemId).findViewById(R.id.tv_content)).setText(content);
        ((TextView) findViewById(itemId).findViewById(R.id.tv_title)).setTextColor(ContextCompat.getColor(this, R.color.levelRed));
        ((TextView) findViewById(itemId).findViewById(R.id.tv_content)).setTextColor(ContextCompat.getColor(this, R.color.levelRed));

    }

    private void setItem(int itemId, String title, String content, boolean isRed) {
        ((TextView) findViewById(itemId).findViewById(R.id.tv_title)).setText(title);
        ((TextView) findViewById(itemId).findViewById(R.id.tv_content)).setText(content);
        if (isRed) {
            ((TextView) findViewById(itemId).findViewById(R.id.tv_title)).setTextColor(ContextCompat.getColor(this, R.color.commonWhite));
            ((TextView) findViewById(itemId).findViewById(R.id.tv_content)).setTextColor(ContextCompat.getColor(this, R.color.commonWhite));
            ((LinearLayout) findViewById(itemId)).setBackground(ContextCompat.getDrawable(App.INSTANCE, R.drawable.level_shape_red));
        } else {
            ((TextView) findViewById(itemId).findViewById(R.id.tv_title)).setTextColor(ContextCompat.getColor(this, R.color.commonWhite));
            ((TextView) findViewById(itemId).findViewById(R.id.tv_content)).setTextColor(ContextCompat.getColor(this, R.color.commonWhite));
            ((LinearLayout) findViewById(itemId)).setBackground(ContextCompat.getDrawable(App.INSTANCE, R.drawable.level_shape_green));

        }
    }

    public void updateTrade(TradeInfoBean bean) {
        this.bean = bean;
        setItem(R.id.trade_item_dtqy, App.INSTANCE.getString(R.string.leveltradeActivity6), CoinUtil.keepUSDT(bean.getAllFound()));
        setItem(R.id.trade_item_kyzj, App.INSTANCE.getString(R.string.leveltradeActivity7), CoinUtil.keepUSDT(bean.getUsableFund()));
        setItem(R.id.trade_item_djbzj, App.INSTANCE.getString(R.string.leveltradeActivity8), CoinUtil.keepUSDT(bean.getHasUsedFund()));
        setItem(R.id.trade_item_fdyk, App.INSTANCE.getString(R.string.leveltradeActivity9), CoinUtil.keepUSDT(bean.getFloatWinLoseFee()), Double.valueOf(bean.getFloatWinLoseFee()) < 0);
//        setItem(R.id.trade_item_pcyk, App.INSTANCE.getString(R.string.levelTradeActivity12), NumberUtil.keepMax4(bean.getCloseWinLoseFee() + ""));
        setItem(R.id.trade_item_fxl, App.INSTANCE.getString(R.string.leveltradeActivity10), CoinUtil.keepRMB(bean.getBlowingUprate()) + "%", "");
    }


    public void updateUI(List<TradeListBean> list) {

        this.list = list;
        updateUI();
    }

    public void updateUI() {
        winLossMoney = new BigDecimal("0");
        for (TradeListBean tradeListBean : list) {
            winLossMoney = winLossMoney.add(new BigDecimal(tradeListBean.getWinLoseMoney()));
        }
        if (bean != null) {
            bean.setFloatWinLoseFee(winLossMoney.toPlainString());
        }
        setItem(R.id.trade_item_fdyk, App.INSTANCE.getString(R.string.leveltradeActivity9), CoinUtil.keepUSDT(winLossMoney.toPlainString()), Double.valueOf(winLossMoney.toPlainString()) < 0);

    }

    public void refreshCoin(CoinBean coinBean) {

        if (list == null) {
            return;
        }
        DisposUtil.close(changePriceDispo);
        changePriceDispo = Flowable.fromIterable(list)
                .filter(tradeListBean -> tradeListBean.getStockCode().equalsIgnoreCase(coinBean.getCode()))
                .filter(tradeListBean -> !tradeListBean.getNewPrice().equals(coinBean.getPrice()))
                .subscribe(tradeListBean -> {
                    tradeListBean.setNewPrice(coinBean.getPrice());
                }, e -> {
                });
        updateUI();

        if (winLossMoney != null && bean != null) {
            BigDecimal allFundBig = new BigDecimal(bean.getUsableFund()).add(new BigDecimal(bean.getHasUsedFund())).add(winLossMoney);
            bean.setAllFound(allFundBig.toPlainString());
            if (Double.valueOf(bean.getHasUsedFund()) == 0) {
                bean.setBlowingUprate("0");
            } else {
                BigDecimal blowBig = allFundBig.divide(new BigDecimal(bean.getHasUsedFund()), 8, RoundingMode.DOWN);
                bean.setBlowingUprate(blowBig.toPlainString());
            }
            updateTrade(bean);
        }

    }

    @Override
    protected void onDestroy() {
        DisposUtil.close(subscribe);

        super.onDestroy();
    }

}
